import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  ManyToOne,
  JoinColumn,
  Index,
} from 'typeorm';
import { User } from '../../auth/entities/user.entity';

/**
 * 通知类型
 */
export enum NotificationType {
  FRIEND_REQUEST = 'friend_request', // 好友请求
  FRIEND_ACCEPTED = 'friend_accepted', // 好友请求被接受
  WORK_LIKED = 'work_liked', // 作品被点赞
  WORK_COLLECTED = 'work_collected', // 作品被收藏
  WORK_COMMENTED = 'work_commented', // 作品被评论
  COMMENT_REPLIED = 'comment_replied', // 评论被回复
  SYSTEM = 'system', // 系统通知
}

/**
 * 系统通知实体
 */
@Entity('notifications')
@Index(['userId', 'isRead']) // 优化未读通知查询
@Index(['userId', 'createdAt']) // 优化通知列表查询
export class Notification {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ comment: '接收者ID' })
  userId: number;

  @Column({ nullable: true, comment: '触发者ID（谁触发了这个通知）' })
  triggerId: number | null;

  @Column({
    type: 'enum',
    enum: NotificationType,
    comment: '通知类型',
  })
  type: NotificationType;

  @Column({ type: 'varchar', length: 200, comment: '通知标题' })
  title: string;

  @Column({ type: 'text', comment: '通知内容' })
  content: string;

  @Column({
    type: 'simple-json',
    nullable: true,
    comment: '关联数据（JSON格式，如作品ID、评论ID等）',
  })
  data: Record<string, any> | null;

  @Column({ default: false, comment: '是否已读' })
  isRead: boolean;

  @Column({ type: 'timestamp', nullable: true, comment: '已读时间' })
  readAt: Date | null;

  @Column({ default: false, comment: '是否已删除' })
  isDeleted: boolean;

  @ManyToOne(() => User, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'userId' })
  user: User;

  @ManyToOne(() => User, { eager: true, onDelete: 'SET NULL' })
  @JoinColumn({ name: 'triggerId' })
  trigger: User | null;

  @CreateDateColumn({ type: 'timestamp', comment: '创建时间' })
  createdAt: Date;
}
